package com.example.warehouse_manager.filter;


import com.alibaba.fastjson.JSON;
import com.example.warehouse_manager.entity.Result;
import com.example.warehouse_manager.utils.WarehouseConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/*
* 自定义的登录限制过滤器
* */
public class LoginCheckFilter implements Filter {


    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //白名单请求放行,创建List<String>放白名单url接口
        List<String> urlList = new ArrayList<>();
        urlList.add("/captcha/captchaImage");
        urlList.add("/login");
        urlList.add("/product/img-upload");

        //过滤器拦截到的当前请求的url接口
        String url = request.getServletPath();
        if (urlList.contains(url) || url.contains("/img/upload")){//放行
            chain.doFilter(request,response);
            return;
        }

        //校验其他请求是否携带token，判断redis中是否存在token键
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //有->放行
        if (StringUtils.hasText(token)&&redisTemplate.hasKey(token)){
            chain.doFilter(request,response);
            return;
        }
        //没有->说明未登录或token过期，请求不放行，并且给前端作出响应
        Result result = Result.err(Result.CODE_ERR_UNLOGINED, "您未登录！");
        String jsonString = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(jsonString);
        out.flush();
        out.close();

    }
}
